//
//  DetailViewController.m
//  FeedBackMod
//
//  Created by sischen on 16/5/14.
//  Copyright (c) 2016年 neo6. All rights reserved.
//

#import "DetailViewController.h"
#import "FeedBackFormView.h"
#import "FeedBackModel.h"

#import "WBPopMenuModel.h"
#import "WBPopMenuSingleton.h"
#import "WBPopMenuView.h"
#import "SopAddPicViewController.h"
#import "UserSites.h"
#import "SopModel.h"
#import "PointValueModel.h"
#import "PointModelOffline.h"

#define SCREEN_W [UIScreen mainScreen].bounds.size.width
#define SCREEN_H [UIScreen mainScreen].bounds.size.height
#define CONTACT_HINT @"请输入联系方式"
#define KEY_H	  252
#define CONTACT_H 60
#define GAP 10 //上升时底部多留的空隙

@interface DetailViewController () <UIScrollViewDelegate, UITextFieldDelegate,UIImagePickerControllerDelegate>
{
	BOOL isKeyBoardShown;
	CGFloat needRise_H;//本次键盘弹出时,view需要上升的高度
	CGFloat needScroll_H;//本次键盘弹出时,如果文本框未展示完全,scrollview需要向上滚动的距离
    
    UIImageView* addPhoto;
}
@property (nonatomic, strong) UIScrollView *scrollerView;
//直接提交问题
@property(nonatomic, strong)NSMutableArray *sopArray;
@property(nonatomic, strong)NSString* sopUuid;
@property(nonatomic, strong)NSString* pointUuid;

@end

@implementation DetailViewController//二维码异常状态页面
-(void)viewWillAppear:(BOOL)animated
{
    self.scrollerView = [[UIScrollView alloc] init];
    self.scrollerView.frame = CGRectMake(0, 0, self.view.bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    if (addPhoto) {
        self.scrollerView.frame = CGRectMake(0, 64, self.view.bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    }
    self.scrollerView.backgroundColor = [UIColor whiteColor];
    self.scrollerView.delegate = self;
    //在这里创建item
    [self createItem];
    
    NSInteger formcount = self.item.formsArray.count;
    CGFloat contentHeight = 0;//累计内容高度
    
    for (NSInteger i = 0; i < formcount; i++) {
        
        FeedBackFormView *formView = [[FeedBackFormView alloc] initWithFrame:CGRectMake(0, contentHeight, self.scrollerView.bounds.size.width, 0) andForm:self.item.formsArray[i]];
        formView.line=self.line;
        if (i==0) {
            formView.form.tag=@"二维码";
        }
        if (i==1) {
            formView.form.tag=@"二维码err";
        }
        [formView disPlayForm];
        
        formView.keyboardBlock = ^void(UITextView *tv){
            NSInteger a=tv.tag;
            [self keyboardRising:tv];
        };
//        formView.block = ^{
//            SopAddPicViewController* detailVC = [[SopAddPicViewController alloc]init];
//            //    detailVC.model = self.aticleArray[indexPath.row];
//            [self.rt_navigationController pushViewController:detailVC animated:YES];
//        };
        formView.blockError = ^(NSString *error, NSString *remark) {
            if ([remark isEqualToString:@""]) {
             self.line.exceptionState=error;
            }
            else
            {
            self.line.exceptionState=error;
            self.line.exceptionRemark=remark;
            }
            if ([_delegate respondsToSelector:@selector(lineSelectedAtIndex:)]) {
                [_delegate lineSelectedAtIndex:_line];
            }
        };
        [self.scrollerView addSubview:formView];
        contentHeight += formView.bounds.size.height;
    }
    
    UITextField *contactTF = [[UITextField alloc] initWithFrame:CGRectMake(SEL_H/4, contentHeight+SEL_H/4, SCREEN_W-SEL_H/2, CONTACT_H-SEL_H/2)];
    contactTF.borderStyle = UITextBorderStyleRoundedRect;
    contactTF.delegate = self;
    contactTF.placeholder = CONTACT_HINT;
    contactTF.font = [UIFont systemFontOfSize:15];
    //添加图片的拍照按钮
    if (!addPhoto) {
    addPhoto=[[UIImageView alloc] initWithFrame:CGRectMake(SEL_H/4, contentHeight+SEL_H/4, SCREEN_W-SEL_H/2, CONTACT_H+SEL_H)];
    [addPhoto setImage:[UIImage imageNamed:@"add_photo"]];
    }
    addPhoto.userInteractionEnabled=YES;
    UITapGestureRecognizer *singleTap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addPic)];
    [addPhoto addGestureRecognizer:singleTap];
    
//    [self.scrollerView addSubview:addPhoto];
    
    UIButton *commitBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    commitBtn.frame = CGRectMake(SEL_H/4, contentHeight+CONTACT_H+SEL_H+SEL_H/2, SCREEN_W-SEL_H/2, CONTACT_H-SEL_H/2);
    [commitBtn setTitle:@"提交" forState:UIControlStateNormal];
    commitBtn.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.1];
    commitBtn.clipsToBounds = YES;
    commitBtn.layer.cornerRadius = 5;
//    [self.scrollerView addSubview:commitBtn];
    
    self.scrollerView.contentSize = CGSizeMake(self.scrollerView.bounds.size.width, contentHeight+CONTACT_H+CONTACT_H);
    [self.view addSubview:self.scrollerView];
    
    UIBarButtonItem *myButton = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleBordered target:self action:@selector(clickEvent)];
    [myButton setTintColor:[UIColor whiteColor]];
    //去掉保存
//    self.navigationItem. rightBarButtonItem = myButton;
    //返回
    self.navigationItem.hidesBackButton = YES;
    UIImage *image = [UIImage imageNamed:@"Back"];
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0, 30, 44);
    backButton.imageEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    [backButton setImage:image forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftItemsSupplementBackButton = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.sopArray = [NSMutableArray array];

	
	
	//监听键盘下降：
	NSNotificationCenter *noticenter = [NSNotificationCenter defaultCenter];
	[noticenter addObserver:self selector:@selector(keyboardDown) name:UIKeyboardWillHideNotification object:nil];
    //去除状态
    [MySingleton sharedMySingleton].exceptionState=nil;
    
    //离线存储
    NSArray * array1 = [PointModelOffline findWhere:@[@"offlineuuid",@"=",self.line.pointNum]];
    NSMutableArray* Temp1=[NSMutableArray new];
    for (PointModelOffline* model in array1) {
        if ([model.pointNum isEqualToString:self.line.pointNum]) {
            PointModel* aa=[PointModel new];
            aa.seq=model.seq;
            aa.title=model.title;
            aa.content=model.content;
            aa.shiftUuid=model.shiftUuid;
            aa.sopUuid=model.sopUuid;
            aa.auditUuid=model.auditUuid;
            aa.pointUuid=model.pointUuid;//pointUuid多个检查点
            aa.categoryName=model.categoryName;
            aa.categoryWeight=model.categoryWeight;
            aa.type=model.type;
            aa.valueArr=model.valueArr;
            aa.picture=model.picture;
            aa.remark=model.remark;
            aa.uuid=_workModel.uuid;//
            aa.pointNum=model.pointNum;
            aa.offlineName=model.offlineName;
            
            [Temp1 addObject:aa];
        }
        
    }
    if (Temp1.count>0) {
        [self.sopArray removeAllObjects];
        [self.sopArray addObjectsFromArray:Temp1];
        
        //排序
        NSArray *sortArray = [self.sopArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            
            PointModel *pModel1 = obj1;
            PointModel *pModel2 = obj2;
            if (pModel1.seq > pModel2.seq) { //不使用intValue比较无效
                return NSOrderedDescending;//降序
            }else if (pModel1.seq < pModel2.seq){
                return NSOrderedAscending;//升序
            }else {
                return NSOrderedSame;//相等
            }
            
        }];
        [self.sopArray removeAllObjects];
        self.sopArray=[NSMutableArray arrayWithArray:sortArray];
        //赋值sopuuid
        for (PointModel* pm in Temp1) {
            _sopUuid=pm.sopUuid;
            _pointUuid=pm.pointUuid;//
            break;
        }
        
    }
    else
    {
        [self postUI];

    }
}
-(void)goBack
{
    [self submitSop];
    [self.rt_navigationController popViewControllerAnimated:YES complete:nil];
}
-(void)submitSop
{
    if ([MySingleton sharedMySingleton].finished) {
        return;
    }
    //执行代理方法
    if ([_delegate respondsToSelector:@selector(SopToRouteTranfer1:pointNum:)]) {
        [_delegate SopToRouteTranfer1:self.sopArray pointNum:self.line.pointNum];
    }
    NSArray * array = [PointModel findWhere:@[@"uuid",@"=",_workModel.uuid]];
    if (array.count>0) {
        //删除sopuuid的pointmodel
        for (PointModel* pm in array) {
            if (_pointUuid)
                [PointModel deleteWhere:@[@"uuid",@"=",_workModel.uuid,@"pointUuid",@"=",_pointUuid]];
        }
    }
    for (PointModel* pm in self.sopArray) {
        [pm saveOrUpdateAsync:^(BOOL isSuccess) {

        }];
    }
}
-(void)postUI{
    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    
    NSDictionary *params = @{
                             @"siteUuid" : self.line.pointUuid
                             };
    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool get:[NSString stringWithFormat:@"digiops/app/SelectPoints"] params:nil success:^(id responseObj) {
        NSLog(@"");
        [self.sopArray removeAllObjects];
        
        for (NSDictionary* sop in responseObj[@"content"]) {
            SopModel* s=[SopModel mj_objectWithKeyValues:sop];
            
            if ([self.line.pointNum isEqualToString:s.pointNum]) {
                for (NSDictionary* temp in s.sopTemplates) {
                    
                    PointModel* p=[PointModel mj_objectWithKeyValues:temp];
                    
                    NSData *data = [p.content dataUsingEncoding:NSUTF8StringEncoding];
                    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                    NSMutableArray* arr=[NSMutableArray new];
                    for (NSDictionary* v in dict) {
                        PointValueModel* model=[PointValueModel mj_objectWithKeyValues:v];
                        [arr addObject:model];
                        
                    }
                    p.valueArr=arr;
                    p.sopUuid=s.pointUuid;
                    _sopUuid=s.pointUuid;
                    p.uuid=_workModel.uuid;
                    p.pointNum=s.pointNum;
                    [self.sopArray addObject:p];
                    
                    NSLog(@"");
                }
            }
            NSLog(@"");
        }
        
        NSLog(@"");
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];

    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        
    }];
}
-(void)clickEvent{
    NSMutableArray *obj = [NSMutableArray array];
    
    for (NSInteger i = 0; i < [self titles].count; i++) {
        
        WBPopMenuModel * info = [WBPopMenuModel new];
        //        info.image = [self images][i];
        info.title = [self titles][i];
        [obj addObject:info];
    }
    
    [[WBPopMenuSingleton shareManager]showPopMenuSelecteWithFrame:150
                                                             item:obj
                                                           action:^(NSInteger index) {
                                                               NSLog(@"index:%ld",(long)index);
                                                               //    detailVC.model = self.aticleArray[indexPath.row];
                                                               [self.rt_navigationController popViewControllerAnimated:YES complete:nil];
                                                               [self submitSop];
                                                           }];
}
- (NSArray *) titles {
    return @[@"保存"];
}

- (NSArray *) images {
    return @[@"right_menu_QR@3x",
             @"right_menu_addFri@3x",
             @"right_menu_multichat@3x",
             @"right_menu_sendFile@3x",
             @"right_menu_facetoface@3x",
             @"right_menu_payMoney@3x"];
}
-(void)createItem
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"quick_form" ofType:@"json"];
    FeedBackModel* model = [[FeedBackModel alloc] initWithJsonFilePath:path];
    self.item=model.indexItemArray[0];
}
- (void)addPic {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
        [self cameraClick];
    }];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
        [self selectPhotos];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction *action) {
    }];
    
    [alertController addAction:cameraAction];
//    [alertController addAction:albumAction];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark 拍摄、相册完成后要执行的方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //得到图片
    UIImage* image = [info objectForKey:UIImagePickerControllerEditedImage];
    [addPhoto setImage:image];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)cameraClick {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController * picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;  //是否可编辑
        //摄像头
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"您没有摄像头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}

- (void)selectPhotos {
    UIImagePickerController * picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;//是否可以编辑
    //打开相册选择照片
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:picker animated:YES completion:nil];
}
-(void)keyboardRising:(UIScrollView *)tv
{
	//正在输入文本框的在window的绝对坐标rect
	CGRect rect = [tv convertRect:tv.bounds toView:[[UIApplication sharedApplication] keyWindow]];
	//h:需要上升的高度
	CGFloat h = rect.origin.y + rect.size.height+GAP + KEY_H - SCREEN_H;
	
	if (h <= 0) {//不需要上升
		return;
	}
	
	//当前scrollerView的偏移
	CGPoint offset = self.scrollerView.contentOffset;
	//h2:需要向上滚的高度
	CGFloat h2 = rect.origin.y + rect.size.height+GAP - SCREEN_H;
	
	if (h2 > 0) {//先滚动scrollerView确保文本框被完全显示
		needScroll_H = h2;
		offset.y += needScroll_H;
		self.scrollerView.contentOffset = offset;
	}

	needRise_H = h;
	CGRect frame = self.view.frame;
	frame.origin.y -= needRise_H - needScroll_H;
	
	NSLog(@"键盘上升了");
	[UIView animateWithDuration:0.3 animations:^{
		self.view.frame = frame;
		isKeyBoardShown = YES;
	}];
}



- (void)keyboardDown
{
	if (!isKeyBoardShown) {
		return;
	}
	
	CGRect frame = self.view.frame;
	frame.origin.y += needRise_H - needScroll_H;
	
	NSLog(@"键盘下降了");
	[UIView animateWithDuration:0.3 animations:^{
		self.view.frame = frame;
		isKeyBoardShown = NO;
		needRise_H = 0;
		needScroll_H = 0;
	}];
}


-(void)textFieldDidBeginEditing:(UITextField *)textField
{
	[self keyboardRising:(UIScrollView *)textField];
}


-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
	[self.scrollerView endEditing:YES];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
	[textField resignFirstResponder];
	return NO;
}



//- (void)didReceiveMemoryWarning {
//    [super didReceiveMemoryWarning];
//    // Dispose of any resources that can be recreated.
//}

@end
